import classNames from 'classnames'
import { useMemo, useState } from 'react'

import { billTypeToName } from '@/contants/'
import BillIcon from '@/components/Icon/'
import './index.scss'

const DailyBill = ({ date, billList }) => {
  /* 日账单统计功能 */
  const dayComputedResult = useMemo(() => {
    // 支出
    const pay = billList
      .filter(item => item.type === 'pay')
      .reduce((prevTotal, currentItem) => prevTotal + currentItem.money, 0)
    // 收入
    const income = billList
      .filter(item => item.type === 'income')
      .reduce((prevTotal, currentItem) => prevTotal + currentItem.money, 0)

    return {
      pay,
      income,
      total: pay + income
    }
  }, [billList])

  /* 日账单列表显示/隐藏 */
  const [showBillList, setShowBillList] = useState(false)

  /* JSX */
  return (
    <div className={classNames('dailyBill')}>
      <div className='header'>
        <div className='dateIcon'>
          <span className='date'>{ date }</span>
          <span
            className={classNames('arrow', showBillList && 'expand')}
            onClick={() => setShowBillList(!showBillList)}
          ></span>
        </div>
        <div className='oneLineOverview'>
          <div className='pay'>
            <span className='type'>支出</span>
            <span className='money'>{ Math.abs(dayComputedResult.pay).toFixed(2) }</span>
          </div>
          <div className='income'>
            <span className='type'>收入</span>
            <span className='money'>{ dayComputedResult.income.toFixed(2) }</span>
          </div>
          <div className='balance'>
            <span className='money'>{ dayComputedResult.total.toFixed(2) }</span>
            <span className='type'>结余</span>
          </div>
        </div>
      </div>
      {/* 单日列表 */}
      <div
        className='billList'
        style={{ display: showBillList ? 'block' : 'none' }}
      >
        {
          billList.map(item => (
            <div className='bill' key={ item.id }>
              <BillIcon type={ item.useFor }/>
              <div className='detail'>
                <div className='billType'>{ billTypeToName[item.useFor] }</div>
              </div>
              <div className={ classNames('money', item.type) }>
                { item.money.toFixed(2) }
              </div>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default DailyBill
